package com.app.util.common;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;



import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.ImageIcon;

import javax.imageio.IIOImage;  
import javax.imageio.ImageTypeSpecifier;  
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import net.coobird.thumbnailator.Thumbnails;

import org.w3c.dom.Element;  

public class ImgString{
	private final static int Base64Format = AndroidBase64.DEFAULT;
	
    /** 
     * @param fromFileStr 
     *            原始图片完整路径 
     * @param saveToFileStr 
     *            缩略图片保存路径 
     * @param sysimgfilenNow 
     *            处理后的图片文件名前缀 
     *  
     */  
    public boolean createThumbnail(String fromFileStr, String saveToFileStr, String sysimgfile, String suffix, int width, int height) throws Exception {  
        //图片的格式 gif\jpg\png  
        double Ratio = 0.0;  
        File F = new File(fromFileStr);  
        if (!F.isFile())  
            throw new Exception(F + " is not image file error in CreateThumbnail!");  
        File ThF = new File(saveToFileStr, sysimgfile +"."+suffix);  
        BufferedImage Bi = ImageIO.read(F);  
        Image Itemp = Bi.getScaledInstance(width, height, 2);  
        if ((Bi.getHeight() > width) || (Bi.getWidth() > height)) {  
            if (Bi.getHeight() > Bi.getWidth())  
                Ratio = (double)width / Bi.getHeight();  
            else  
                Ratio = (double)height / Bi.getWidth();  
        }  
        AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(Ratio, Ratio), null);  
        Itemp = op.filter(Bi, null);  
        try {  
            ImageIO.write((BufferedImage) Itemp, suffix, ThF);  
        } catch (Exception ex) {  
            throw new Exception(" ImageIo.write error in CreatThum.: " + ex.getMessage());  
        }  
        return true;  
    }
    
    /**
     * 创建图片缩略图(等比缩放)
     * 
     * @param chenkf
     */
	public void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {  
		if (!originalFile.exists()) {
	        System.out.println("文件不存在");
	        return;
	    }
    	if (quality > 1) {  
            throw new IllegalArgumentException("Quality has to be between 0 and 1");  
        }  
        ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());  
        Image i = ii.getImage();  
        Image resizedImage = null;  
        int iWidth = i.getWidth(null);  
        int iHeight = i.getHeight(null);  
        if (iWidth > iHeight) {  
            resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);  
        } else {  
            resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);  
        }  
        // This code ensures that all the pixels in the image are loaded.  
        Image temp = new ImageIcon(resizedImage).getImage();  
        // Create the buffered image.  
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);  
        // Copy image to buffered image.  
        Graphics g = bufferedImage.createGraphics();  
        // Clear background and paint the image.  
        g.setColor(Color.white);  
        g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));  
        g.drawImage(temp, 0, 0, null);  
        g.dispose();  
  
        // Soften.  
        float softenFactor = 0.05f;  
        float[] softenArray = { 0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 };  
        Kernel kernel = new Kernel(3, 3, softenArray);  
        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);  
        bufferedImage = cOp.filter(bufferedImage, null);  
  
        // Write the jpeg to a file.  
        FileOutputStream out = new FileOutputStream(resizedFile);  
  
        // Encodes image as a JPEG data stream  
//        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
//        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
//        
//        param.setQuality(quality, true);  
//        encoder.setJPEGEncodeParam(param);  
//        encoder.encode(bufferedImage); 
        
        
        saveAsJPEG(100, bufferedImage, quality, out);
    }
    
    /**
     * 创建图片缩略图(等比缩放)
     * 
     * @param src
     *            源图片文件完整路径
     * @param dist
     *            目标图片文件完整路径
     * @param width
     *            缩放的宽度
     * @param height
     *            缩放的高度
     */
    public void createThumbnail(String src, String dist, float width, float height) {
        try {
            File srcfile = new File(src);
            if (!srcfile.exists()) {
                System.out.println("文件不存在");
                return;
            }
            BufferedImage image = ImageIO.read(srcfile);

            // 获得缩放的比例
            double ratio = 1.0;
            // 判断如果高、宽都不大于设定值，则不处理
            if (image.getHeight() > height || image.getWidth() > width) {
                if (image.getHeight() > image.getWidth()) {
                    ratio = height / image.getHeight();
                } else {
                    ratio = width / image.getWidth();
                }
            }
            // 计算新的图面宽度和高度
            int newWidth = (int) (image.getWidth() * ratio);
            int newHeight = (int) (image.getHeight() * ratio);

            BufferedImage bfImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            bfImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);

            FileOutputStream os = new FileOutputStream(dist);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
//            encoder.encode(bfImage);
            saveAsJPEG(100, bfImage, 2f, os);
            os.close();
            System.out.println("创建缩略图成功");
        } catch (Exception e) {
            System.out.println("创建缩略图发生异常" + e.getMessage());
        }
    }
	
	/**
	 * 横向拼接一组（多张）图像
	 * 
	 * @param pics
	 *            将要拼接的图像
	 * @param type
	 *            图像写入格式
	 * @param dst_pic
	 *            图像写入路径
	 * @return
	 */
	public String joinImageListHorizontal(ArrayList<byte[]> bytes, String type, String filePath, String fileName) {
		try {
			initPath(filePath);
			String dst_pic = filePath+fileName;
			int len = bytes.size();
			if (len < 1) {
				System.out.println("pics len < 1");
				return null;
			}

			BufferedImage[] images = new BufferedImage[len];
			int[][] imageArrays = new int[len][];
			for (int i = 0; i < len; i++) {
				ByteArrayInputStream bin = new ByteArrayInputStream(bytes.get(i));
				images[i] = ImageIO.read(bin);
				int width = images[i].getWidth();
				int height = images[i].getHeight();
				imageArrays[i] = new int[width * height];// 从图片中读取RGB
				imageArrays[i] = images[i].getRGB(0, 0, width, height, imageArrays[i], 0, width);
			}

			int dst_width = 0;
			int dst_height = images[0].getHeight();
			for (int i = 0; i < images.length; i++) {
				dst_height = dst_height > images[i].getHeight() ? dst_height : images[i].getHeight();
				dst_width += images[i].getWidth();
			}
			//System.out.println("dst_width===chenkf==="+dst_width);
			//System.out.println("dst_height===chenkf==="+dst_height);
			if (dst_height < 1) {
				System.out.println("dst_height < 1");
				return null;
			}
			/*
			 * 生成新图片
			 */
			BufferedImage ImageNew = new BufferedImage(dst_width, dst_height, 2);
			int width_i = 0;
			//System.out.println("dst_height====="+dst_height);
			for (int i = 0; i < images.length; i++) {
				if(images[i].getHeight()<dst_height){
					//System.out.println("images[i].getHeight()====="+images[i].getHeight());
					ImageNew.setRGB(width_i, dst_height-images[i].getHeight(), images[i].getWidth(), images[i].getHeight(), imageArrays[i], 0, images[i].getWidth());
				}else{
					ImageNew.setRGB(width_i, 0, images[i].getWidth(), images[i].getHeight(), imageArrays[i], 0, images[i].getWidth());
				}
				width_i += images[i].getWidth();
			}
			File outFile = new File(dst_pic);
			ImageIO.write(ImageNew, type, outFile);// 写图片
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return fileName;
	}
	
	/** 
	* 计算字符串中同一个字符出现的次数 
	*/
	public int stringNumbers(String strValue,String str){
		int counter = 0;
		int length = 0;
		if(!"".equals(str)){
			length = str.length();
		}
        if(strValue.indexOf(str)==-1){
            return 0;
        }else if(strValue.indexOf(str) != -1){
            counter++;
            stringNumbers(strValue.substring(strValue.indexOf(str)+length),str);
            return counter;
        }
        return 0;
    }
	
	/** 
	* 删除某个文件夹下的所有文件夹和文件 
	* @param delpath String 
	* @throws FileNotFoundException 
	* @throws IOException 
	* @return boolean 
	*/ 
	public boolean deletefile(String delpath) throws FileNotFoundException,IOException {
		try{
			File file = new File(delpath); 
			if(!file.isDirectory()) {
				System.out.println("1"); 
				file.delete(); 
			}else if (file.isDirectory()) {
				System.out.println("2"); 
				String[] filelist = file.list(); 
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + "\\" + filelist[i]); 
					if (!delfile.isDirectory()) {
						System.out.println("path=" + delfile.getPath()); 
						System.out.println("absolutepath=" + delfile.getAbsolutePath()); 
						System.out.println("name=" + delfile.getName()); 
						delfile.delete(); 
						//System.out.println("删除文件成功"); 
					}else if (delfile.isDirectory()) {
						deletefile(delpath + "\\" + filelist[i]); 
					} 
				} 
				file.delete(); 
			} 
		}catch (FileNotFoundException e) { 
			System.out.println("deletefile() Exception:" + e.getMessage()); 
			return false;
		} 
		return true; 
	}
	
	// Linux下删除指定文件夹下所有文件  
	public void deleteAllFilesOfDir(File path) {  
	    if (!path.exists())  
	        return;  
	    if (path.isFile()) {  
	        path.delete();  
	        return;  
	    }  
	    File[] files = path.listFiles();  
	    for (int i = 0; i < files.length; i++) {  
	        deleteAllFilesOfDir(files[i]);  
	    }  
	    path.delete();  
	}  
	
	// 删除指定文件夹下所有文件  
    // param path 文件夹完整绝对路径  
    public boolean delAllFile(String path) {  
        boolean flag = false;  
        File file = new File(path);  
        if (!file.exists()) {  
            return flag;  
        }  
        if (!file.isDirectory()) {  
            return flag;  
        }  
        String[] tempList = file.list();  
        File temp = null;  
        for (int i = 0; i < tempList.length; i++) {  
            if (path.endsWith(File.separator)) {  
                temp = new File(path + tempList[i]);  
            } else {  
                temp = new File(path + File.separator + tempList[i]);  
            }  
            if (temp.isFile()) {  
                temp.delete();  
            }  
            if (temp.isDirectory()) {  
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件  
//              delFolder(path + "/" + tempList[i]);// 再删除空文件夹  
                flag = true;  
            }  
        }  
        return flag;  
    }

	public String xPic(String onePicPath, String twoPicPath, String filePath, String fileName, int kgSize){//横向处理图片  
        try {
        	initPath(filePath);
			String picOne = filePath+onePicPath;
			String picTwo = filePath+twoPicPath;
			String picBorn = filePath+fileName;
            /* 1 读取第一张图片*/   
            //File fileOne = new File("E:\\1.png");  
        	File fileOne = new File(picOne);
            BufferedImage imageFirst = ImageIO.read(fileOne);  
            int width1 = imageFirst.getWidth();// 图片宽度  
            int height1 = imageFirst.getHeight();// 图片高度  
            int[] imageArrayFirst = new int[width1 * height1];// 从图片中读取RGB  
            imageArrayFirst = imageFirst.getRGB(0, 0, width1, height1, imageArrayFirst, 0, width1);  

            /* 1 对第二张图片做相同的处理 */  
            //File fileTwo = new File("E:\\2.png");  
            File fileTwo = new File(picTwo);  
            BufferedImage imageSecond = ImageIO.read(fileTwo); 
            int width2 = imageSecond.getWidth();// 图片宽度  
            int height2 = imageSecond.getHeight();// 图片高度  
            int[] imageArraySecond = new int[width2 * height2];  
            imageArraySecond = imageSecond.getRGB(0, 0, width2, height2, imageArraySecond, 0, width2);  

            // 生成新图片   
            int width = width1+width2;
            if(kgSize>0){
            	width = width1+width2+kgSize*10;
            }
            int height = height1>height2?height1:height2;
            System.out.println("width1==="+width1);
            System.out.println("width2==="+width2);
            System.out.println("width==="+width);
            System.out.println("height1==="+height1);
            System.out.println("height2==="+height2);
            System.out.println("height==="+height);
            BufferedImage imageResult = new BufferedImage(width, height, 2);  
            imageResult.setRGB(0, 0, width1, height1, imageArrayFirst, 0, width1);// 设置左半部分的RGB  
            imageResult.setRGB(width2+kgSize*8, 0, width2, height2, imageArraySecond, 0, width2);// 设置右半部分的RGB  
            File outFile = new File(picBorn);  
            ImageIO.write(imageResult, "png", outFile);// 写图片  
        } catch (Exception e) {
            e.printStackTrace();  
        }
        return fileName;
    }
      
    public String yPic(String onePicPath, String twoPicPath, String filePath, String fileName, int hhSize){//纵向处理图片  
        try {
        	initPath(filePath);
			String picOne = filePath+onePicPath;
			String picTwo = filePath+twoPicPath;
			String picBorn = filePath+fileName;
            /* 1 读取第一张图片*/   
            //File fileOne = new File("D:\\1.GIF");  
            File fileOne = new File(picOne);  
            BufferedImage imageFirst = ImageIO.read(fileOne);  
            int width1 = imageFirst.getWidth();// 图片宽度  
            int height1 = imageFirst.getHeight();// 图片高度  
            int[] imageArrayFirst = new int[width1 * height1];// 从图片中读取RGB  
            imageArrayFirst = imageFirst.getRGB(0, 0, width1, height1, imageArrayFirst, 0, width1);  

            /* 1 对第二张图片做相同的处理 */  
            //File fileTwo = new File("D:\\1.GIF");  
            File fileTwo = new File(picTwo);  
            BufferedImage imageSecond = ImageIO.read(fileTwo);  
            int width2 = imageSecond.getWidth();// 图片宽度  
            int height2 = imageSecond.getHeight();// 图片高度  
            int[] imageArraySecond = new int[width2 * height2];  
            imageArraySecond = imageSecond.getRGB(0, 0, width2, height2, imageArraySecond, 0, width2);  

            // 生成新图片   
            int height = height1+height2;
            if(hhSize>0){
            	height = height1+height2+hhSize*10;
            }
            int width = width1>width2?width1:width2;
            System.out.println("height1==="+height1);
            System.out.println("height2==="+height2);
            System.out.println("height==="+height);
            System.out.println("width1==="+width1);
            System.out.println("width2==="+width2);
            System.out.println("width==="+width);
            BufferedImage imageResult = new BufferedImage(width, height, 2);  
            imageResult.setRGB(0, 0, width1, height1, imageArrayFirst, 0, width1);// 设置上半部分的RGB  
            imageResult.setRGB(0, height2+hhSize*8, width2, height2, imageArraySecond, 0, width2);// 设置下半部分的RGB  
            File outFile = new File(picBorn);  
            ImageIO.write(imageResult, "png", outFile);// 写图片  
        } catch (Exception e) {
            e.printStackTrace();  
        }
        return fileName;
    }
    
    /**合并多张图片
    * Merge all pics in one
    * #############
    * # pic1 #
    * #############
    * # pic2 #
    * #############
    * # pic3 #
    * #############
    *
    * @param pics
    * @param dst_pic
    * @return
    */
    public boolean merge(String[] pics, String dst_pic, String type, String filePath, int hhSize, int intType) {
	    int len = pics.length;
	    if (len < 1) {
		    System.out.println("pics len < 1");
		    return false;
	    }
	    File[] src = new File[len];
	    BufferedImage[] images = new BufferedImage[len];
	    int[][] ImageArrays = new int[len][];
	    String picPath = "";
	    for (int i = 0; i < len; i++) {
		    try {
		    	picPath = filePath+pics[i];
			    src[i] = new File(picPath);
			    images[i] = ImageIO.read(src[i]);
		    } catch (Exception e) {
			    e.printStackTrace();
			    return false;
		    }
		    int width = images[i].getWidth();
		    int height = images[i].getHeight();
		    ImageArrays[i] = new int[width * height];// 从图片中读取RGB
		    ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);
	    }
	    int dst_width = 0;
	    int dst_height = 0;
	    if(intType==1){//横向合并
	    	dst_width = 0;
	    	dst_height = images[0].getHeight();
	    }else if(intType==2){//纵向合并
	    	dst_width = images[0].getWidth();
	    	dst_height = 0;
	    }
	    if(intType==1){//横向合并
	    	for (int i = 0; i < images.length; i++){
	    		dst_height = dst_height > images[i].getHeight() ? dst_height : images[i].getHeight();
	    		dst_width += images[i].getWidth()+hhSize*3;
		    }
		    if (dst_width < 1) {
			    System.out.println("dst_width < 1");
			    return false;
		    }
	    }else if(intType==2){//纵向合并
	    	for (int i = 0; i < images.length; i++){
		    	dst_width = dst_width > images[i].getWidth() ? dst_width : images[i].getWidth();
		    	dst_height += images[i].getHeight()+hhSize*3;
		    }
		    if (dst_height < 1) {
			    System.out.println("dst_height < 1");
			    return false;
		    }
	    }
	    // 生成新图片
	    try {
		    //int dst_width = images[0].getWidth();
	    	//int dst_height = images[0].getHeight();
		    BufferedImage ImageNew = new BufferedImage(dst_width,dst_height, 2);
		    int height_i = 0;
		    int width_i = 0;
		    for (int i = 0; i < images.length; i++) {
		    	if(intType==1){//横向合并
		    		ImageNew.setRGB(width_i+hhSize*2, 0, images[i].getWidth(), images[i].getHeight(), ImageArrays[i], 0, images[i].getWidth());
				    if(hhSize>0){
				    	width_i += images[i].getWidth()+hhSize*3;
		            }else{
		            	width_i += images[i].getWidth();
		            }
		    	}else if(intType==2){//纵向合并
		    		ImageNew.setRGB(0, height_i+hhSize*2, images[i].getWidth(), images[i].getHeight(), ImageArrays[i], 0, images[i].getWidth());
				    if(hhSize>0){
				    	height_i += images[i].getHeight()+hhSize*3;
		            }else{
		            	height_i += images[i].getHeight();
		            }
		    	}
		    }
		    File outFile = new File(filePath+dst_pic);
		    ImageIO.write(ImageNew, type, outFile);// 写图片
	    } catch (Exception e) {
		    e.printStackTrace();
		    return false;
	    }
	    return true;
    }
	
	/** 
     * 将byte数组转换成InputStream 
     * @param in 
     * @return 
     * @throws Exception 
     */  
    public InputStream byteTOInputStream(byte[] in) throws Exception {  
        ByteArrayInputStream is = new ByteArrayInputStream(in);  
        return is;  
    }
    
    /**
     * 
     * @param imageURL 输入图片的URL完整路径，可以是本地文件，也可以是网路上的文件
     * @param localPath 保存在本地的路径
     * @throws Exception
     */
    public void CopyImageFromURL(String imageURL, String localPath) throws Exception {
	    // 取得文件后缀名
	    String tmpImageURL = imageURL.toLowerCase();
	    String regex = "(\\.)(gif|bmp|png|dib|jpg|jpeg|jfif)";
	    Pattern pattern = Pattern.compile(regex);
	    Matcher matcher = pattern.matcher(tmpImageURL);
	    if (!matcher.find()) {
	    	throw new Exception("不支持该格式文件.");
	    }
	    URL url;
	    if (imageURL.toLowerCase().startsWith("http")) {// http url
	    	url = new URL(imageURL);
	    } else {// 文件url
		    String tmpUrl = imageURL.toLowerCase();
		    String beginer = tmpUrl.split("/")[0];
		    //if (beginer.matches("[c-o]:")) {// 路径支持到c:d:....o:
		    	url = new File(imageURL).toURL();
		    //} else {
		    	//throw new Exception("无法解析文件URL.");
		    //}
	    }
	    BufferedImage src = ImageIO.read(url);
	    int width = src.getWidth(null);
	    int height = src.getHeight(null);
	    //保存图像到本地
	    int lastSep1 = localPath.lastIndexOf("/");
	    int lastSep2 = localPath.lastIndexOf("\\");
	    int lastSep = (lastSep1>=lastSep2?lastSep1:lastSep2);
	    String path = localPath.substring(0,lastSep);
	    File localDir = new File(path);
	    if (!localDir.exists()) {
	    	localDir.mkdirs();
	    }
	    BufferedImage outImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
	    outImg.getGraphics().drawImage(src, 0, 0, width, height, Color.WHITE, null);
	    FileOutputStream out = new FileOutputStream(localPath);
//	    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 
//	    encoder.encode(outImg);
	    
	    saveAsJPEG(100, outImg, 2f, out);
	    out.close();
    }
    
    /**
     * 
     * 处理一个图片使其居中显示--------现在是白色背景的，想做成透明的背景怎么改
     * @param BufferedImage srcImage 图片对像
     * @param File descFile 目标图片文件
     * @param String suffix_src 图片扩展名
     * @param int destWidth 新图片的宽
     * @param int destHight 新图片的长
     */
    public boolean reduceImage_scale(final BufferedImage srcImage, File descFile, String suffix_src, int destWidth, int destHight) {
        BufferedImage outImage = null;
        try {
            outImage = new BufferedImage(destWidth, destHight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = (Graphics2D) outImage.getGraphics();
            // 设置背景颜色
            graphics2D.setBackground(Color.WHITE);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.0f));
            graphics2D.clearRect(0, 0, destWidth, destHight);
            int oldheight = srcImage.getHeight();
            int oldwidth = srcImage.getWidth();
            // 设置图片居中显示
            //graphics2D.drawImage(srcImage, (destWidth - oldwidth) / 2, (destHight - oldheight) / 2, null);
            ImageIO.write(outImage, suffix_src, descFile);
        }
        catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
	public void initPath(String strDirPath) {
	     java.io.File file_dir = new java.io.File(String.valueOf(strDirPath));
	     if (!file_dir.exists())
	         file_dir.mkdirs();
	}
	
    public void uploadFile(String filePath,String fileName,InputStream is) throws IOException {
    	initPath(filePath);
		OutputStream os = new FileOutputStream(filePath+fileName);
		byte[] buffer = new byte[1024 * 8];
		int len;
		while((len=is.read(buffer))!=-1){
		    os.write(buffer,0,len);
		}
		os.close();
		is.close();
	}
    
	public byte[] generateImage(String imgStr) throws Exception {//对字节数组字符串进行Base64解码并生成图片
		try {
			byte[] bitmapArray=null;
			ArrayList<ImagObject> lists = new Gson().fromJson(imgStr, new TypeToken<ArrayList<ImagObject>>(){}.getType());
			for(ImagObject o:lists){
				bitmapArray = AndroidBase64.decode(Format.formatString(o.getImageString()), Base64Format);
			}
			return bitmapArray;
		} catch (Exception e) { 
			throw e;
		}
	}
	
	public String generateImage(String strPath,String fileName,String imgStr) throws Exception {//对字节数组字符串进行Base64解码并生成图片
		try {
			byte[] bitmapArray=null;
			ArrayList<byte[]> srcArrays = new ArrayList<byte[]>();
			ArrayList<ImagObject> lists = new Gson().fromJson(imgStr, new TypeToken<ArrayList<ImagObject>>(){}.getType());
			if(lists.size()>0){
				for(ImagObject o:lists){
					if(o.getImageString()!=null && !"".equals(o.getImageString())){
						bitmapArray = AndroidBase64.decode(Format.formatString(o.getImageString()), Base64Format);
						srcArrays.add(bitmapArray);
					}
				}
				joinImageListHorizontal(srcArrays,"png",strPath,fileName);
			}
			return fileName;
		} catch (Exception e) {
			throw e;
		}
	}
	
	public class ImagObject {
		private String imageString;
		private String crlfString;
		private String spaceString;

		public String getImageString() {
			return imageString;
		}

		public void setImageString(String imageString) {
			this.imageString = imageString;
		}

		public String getCrlfString() {
			return crlfString;
		}

		public void setCrlfString(String crlfString) {
			this.crlfString = crlfString;
		}

		public String getSpaceString() {
			return spaceString;
		}

		public void setSpaceString(String spaceString) {
			this.spaceString = spaceString;
		}
	}
	
	public String toImg(String picUrl,String picName,String imgStr) {
		try{
			return generateImage(picUrl,picName,imgStr);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/** 
       * 以JPEG编码保存图片 
       * @param dpi  分辨率 
       * @param image_to_save  要处理的图像图片 
       * @param JPEGcompression  压缩比 
       * @param fos 文件输出流 
       * @throws IOException 
       */  
      public static void saveAsJPEG(Integer dpi ,BufferedImage image_to_save, float JPEGcompression, FileOutputStream fos) throws IOException {  
              
          //useful documentation at http://docs.oracle.com/javase/7/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html  
          //useful example program at http://johnbokma.com/java/obtaining-image-metadata.html to output JPEG data  
          
          //old jpeg class  
          //com.sun.image.codec.jpeg.JPEGImageEncoder jpegEncoder  =  com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(fos);  
          //com.sun.image.codec.jpeg.JPEGEncodeParam jpegEncodeParam  =  jpegEncoder.getDefaultJPEGEncodeParam(image_to_save);  
          
         // Image writer  
//        JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();  
          ImageWriter imageWriter  =   ImageIO.getImageWritersBySuffix("jpg").next();  
          ImageOutputStream ios  =  ImageIO.createImageOutputStream(fos);  
          imageWriter.setOutput(ios);  
          //and metadata  
          IIOMetadata imageMetaData  =  imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image_to_save), null);  
             
             
          if(dpi !=  null && !dpi.equals("")){  
                 
               //old metadata  
              //jpegEncodeParam.setDensityUnit(com.sun.image.codec.jpeg.JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);  
              //jpegEncodeParam.setXDensity(dpi);  
              //jpegEncodeParam.setYDensity(dpi);  
          
              //new metadata  
              Element tree  =  (Element) imageMetaData.getAsTree("javax_imageio_jpeg_image_1.0");  
              Element jfif  =  (Element)tree.getElementsByTagName("app0JFIF").item(0);  
              jfif.setAttribute("Xdensity", Integer.toString(dpi) );  
              jfif.setAttribute("Ydensity", Integer.toString(dpi));  
                 
          }  
          
          
          if(JPEGcompression >= 0 && JPEGcompression <= 1f){  
          
              //old compression  
              //jpegEncodeParam.setQuality(JPEGcompression,false);  
          
              // new Compression  
              JPEGImageWriteParam jpegParams  =  (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();  
              jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);  
              jpegParams.setCompressionQuality(JPEGcompression);  
          
          }  
          
          //old write and clean  
          //jpegEncoder.encode(image_to_save, jpegEncodeParam);  
          
          //new Write and clean up  
         imageWriter.write(imageMetaData, new IIOImage(image_to_save, null, null), null);  
          ios.close();  
          imageWriter.dispose();  
          
      } 

      /**
    	 * 缩略图压缩
    	 * @param picPath 压缩前图片路径
    	 * @return String 压缩后图片路径
    	 * @throws IOException
    	 */
    	public String picCompress(String picPath) throws IOException{ 
    		
    		//获取Tomcat根目录	
    		String path = SysConfig.getProString("PATH_ROOT_SYSTEM");
    		
    		//通过.分割
    		String temp[]=picPath.split("\\.");
    		//缩略前文件路径名
    		String name=temp[0];
    		//缩略前文件路径后缀
    		String suffix=temp[temp.length-1];
    		
    		//写入缩略前文件
    		Thumbnails.of(path+picPath)
    		.scale(0.5f)//等比压缩
    		.outputQuality(0.5f)//压缩画质质量
    		.toFile(path+name+"_com."+suffix);//写入压缩后文件地址
    		
    		return name+"_com."+suffix;
    	}
        
	
	public static void main(String[] args) {
		//new ImgString().xPic("1.png", "2.png", "E:\\", "3.png", 3);
		new ImgString().yPic("strAuditSendDocKg1.png", "strAuditSendDocHh1.png", "D:\\Tomcat6\\webapps\\aehg\\upload\\temp\\print\\", "strAuditSendDocHh.png", 3);
	}
	
	
}
